<?php

namespace common\logics\trade\broadcast;

use Yii;
use yii\base\Exception;
use common\models\trade\Trade;
use common\logics\trade\scope\CompatibleScopeInterface;

/**
 * 商城业务订单-回调通知处理
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
abstract class BusinessNotifyBaseModel extends \common\base\Model {

    /**
     * @var Trade 交易信息
     */
    public $trade;

    /**
     * @var string 业务通知订单模型类名
     */
    public $modelClass;

    /**
     * @var CompatibleScopeInterface 业务订单模型
     */
    private $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            ['trade', 'validateTrade'],
        ];
    }

    /**
     * This validate Trade attribute value.
     * 
     * @param string $attribute
     * @return mixed
     */
    public function validateTrade($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $trade = $this->$attribute;
        if (empty($trade)) {
            return $this->addError($attribute, '交易信息不存在');
        }
        Yii::error([
            '收到业务通知',
            $trade->attributes
        ], 'payment');
        $model = null;
        $modelClass = $this->modelClass;
        if ($modelClass && $modelClass::instance() instanceof CompatibleScopeInterface) {
            $model = $modelClass::findByBizno($trade->bizno);
        }
        if (!$model) {
            return $this->addError($attribute, '业务订单【' . $trade->bizno . '】不存在！');
        }
        $this->_model = $model;
    }

    /**
     * 获取业务订单模型信息
     * @return CompatibleScopeInterface
     */
    public function getOrderModel() {
        return $this->_model;
    }

    /**
     * 处理支付消息业务通知
     * @return bool
     */
    public function notify() {
        if (!$this->validate()) {
            return false;
        }
        try {
            $data = $this->executeTransaction('notify');
        } catch (Exception $exc) {
            $this->addError('modelClass', $exc->getMessage());
            return false;
        } catch (Throwable $t) {
            $this->addError('modelClass', $t->getMessage());
            return false;
        }
        return $data;
    }

    /**
     * 业务订单通知处理方法
     * @return bool
     */
    abstract public function transactNotify();
}
